package yxy.apple.http.request;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.util.EntityUtils;

import yxy.apple.http.HTTPException;
import yxy.apple.util.IDGenerator;
import yxy.apple.util.IDGenerator.LetterCase;
import yxy.apple.util.http.HTTPProtocol;

public class MultipartFormDataRequest extends PostRequest<byte[]> {

	private MultipartEntityBuilder builder = MultipartEntityBuilder.create();

	public MultipartFormDataRequest(String url) {
		this(url, IDGenerator.nextLetterSequence(16, LetterCase.RandomCase));
	}

	public MultipartFormDataRequest(String url, String boundary) {
		super(url);
		builder.setBoundary(boundary);
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		String type = HTTPProtocol.MimeType.MultipartFormData;
		if (boundary != null) {
			type += "; boundary=";
			type += boundary;
		}
		this.setHeader(HTTPProtocol.HeaderKey.ContentType, type);
	}

	@Deprecated
	public void setBody(byte[] body) {
		super.setBody(body);
	}

	@Override
	protected String bodyToString(byte[] body) {
		try {
			return new String(this.encodedBody());
		} catch (HTTPException e) {
			return e.getLocalizedMessage();
		}
	}

	public void addTextPart(String field, String value) {
		this.builder.addTextBody(field, value, ContentType.TEXT_PLAIN);
	}

	/**
	 * 
	 * @param field
	 * @param value
	 *            最大长度25k
	 * @param type
	 * @param filename
	 */
	public void addBinaryPart(String field, byte[] value, ContentType type, String filename) {
		this.builder.addBinaryBody(field, value, type, filename);
	}

	@Override
	public byte[] encodedBody() throws HTTPException {
		try {
			HttpEntity entity = builder.build();
			return EntityUtils.toByteArray(entity);
		} catch (IOException e) {
			throw new HTTPException(e);
		}
	}

}
